package com.example.oauthserver.provider;

import com.example.oauthserver.model.RoleDO;
import com.example.oauthserver.model.UserDO;
import com.example.oauthserver.repository.RoleRepository;
import com.example.oauthserver.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UserAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private RoleRepository roleRepository;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        UserDO userDO = (UserDO) userDetailsService.loadUserByUsername(username);
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String,String[]> maps = request.getParameterMap();
        if (userDO.getStatus().equals(1)) {
            throw new BadCredentialsException("禁止登录，改账户已被锁定");
        }else if(userDO.getStatus().equals(2)){
            throw new BadCredentialsException("登录失败，用户已被停用");
        }
        List<RoleDO> roles = roleRepository.findByRoleId(userDO.getId());
        List<GrantedAuthority> authorities = roles.stream().map(RoleDO::getName).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        userDO.setAuthorities(authorities);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDO,password,userDO.getAuthorities());
        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
